package com.loong.tool.lang;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;

/**
 * 图像处理类
 */
public class Images {

	/**
	 * 图片缩放
	 * 
	 * @param file 文件
	 * @param max 大小
	 * @param target 缩放后文件
	 * @return 是否成功
	 * @throws IOException
	 */
	public static boolean resize(File file, int max, File target) throws IOException {

		Image image = ImageIO.read(file);
		if (image == null) {
			throw new IOException("File is not an image");
		}
		// 获取宽高
		int w = image.getWidth(null);
		int h = image.getHeight(null);
		if (w > h)
			return resize(image, max, (max * h) / w, getFormat(file), target);
		else
			return resize(image, (max * w) / h, max, getFormat(file), target);
	}

	/**
	 * 图片缩放
	 * 
	 * @param file 文件
	 * @param width 宽
	 * @param height 高
	 * @param target 缩放后文件
	 * @return 是否成功
	 * @throws IOException
	 */
	public static boolean resize(File file, int width, int height, File target) throws IOException {

		Image image = ImageIO.read(file);
		if (image == null) {
			throw new IOException("File is not an image");
		}
		return resize(image, width, height, getFormat(file), target);
	}

	/**
	 * 图片缩放
	 * 
	 * @param image 图片
	 * @param width 宽
	 * @param height 高
	 * @param format 图片格式
	 * @param target 缩放后文件
	 * @return 是否成功
	 * @throws IOException
	 */
	private static boolean resize(Image image, int width, int height, String format, File target) throws IOException {

		// 图像对象
		Image ti = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
		// 处理图像
		Image temp = new ImageIcon(ti).getImage();
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.createGraphics();
		g.setColor(Color.white);
		g.fillRect(0, 0, width, height);
		g.drawImage(temp, 0, 0, null);
		g.dispose();
		return ImageIO.write(bi, format, target);
	}

	/**
	 * 获取图片格式
	 * 
	 * @param file 文件
	 * @return 文件类型
	 * @throws IOException
	 */
	public static String getFormat(File file) throws IOException {

		ImageInputStream is = null;
		try {
			// 获取图片流
			is = ImageIO.createImageInputStream(file);
			// 获取遍历器
			Iterator<ImageReader> iter = ImageIO.getImageReaders(is);
			if (!iter.hasNext()) {
				throw new IOException("File is not an image");
			}
			ImageReader reader = iter.next();
			// 获取图片格式
			return reader.getFormatName();
		} catch (IOException e) {
			throw e;
		} finally {
			if (is != null)
				try {
					is.close();
				} catch (IOException e) {
				}
		}
	}
}
